package cn.edu.cqie.controller;

import java.util.HashMap;
import java.util.Map;

import javax.validation.Valid;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;

import cn.edu.cqie.bo.LoginBo;
import cn.edu.cqie.config.ResultBean;
import cn.edu.cqie.dto.LoginRequestDto;
import cn.edu.cqie.enums.RespToAppEnum;
import cn.edu.cqie.service.LoginService;

@RestController
@RequestMapping("/login")
public class LoginController {

	private final static Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	private LoginService loginService;

	@PostMapping("/wxLogin")
	@ResponseBody
	public ResultBean wxLogin(@RequestBody @Valid LoginRequestDto dto, BindingResult bindingResult) {

		logger.info("Login-Login-LoginRequest,{}", JSONObject.toJSONString(dto));

		Map<String, Object> result = new HashMap<String, Object>();

		// 1.参数校验
		if (bindingResult.hasErrors()) {
			String message = bindingResult.getFieldError().getDefaultMessage();

			logger.error(RespToAppEnum.BADREQUEST.getCode(), RespToAppEnum.BADREQUEST.getMessage() + ":" + message);
			return ResultBean.error(RespToAppEnum.BADREQUEST.getCode(),
					RespToAppEnum.BADREQUEST.getMessage() + ":" + message);
		}

		// 2封装业务逻辑对象bo
		LoginBo bo = new LoginBo();
		BeanUtils.copyProperties(dto, bo);

		// 3业务逻辑处理
		loginService.wxLogin(bo);

		result.put("token", bo.getToken());// token返回给前端

		logger.info("Login-Login-LoginResp,{}", JSONObject.toJSONString(result));

		return ResultBean.success(result);
	}

}
